package org.cht.webapp.action;

import com.opensymphony.xwork2.Preparable;
import org.cht.service.GenericManager;
import org.cht.model.Contact;
import org.cht.webapp.action.BaseAction;

import java.util.List;

public class ContactAction extends BaseAction implements Preparable {
    private GenericManager<Contact, Long> contactManager;
    private List contacts;
    private Contact contact;
    private Long  id;

    public void setContactManager(GenericManager<Contact, Long> contactManager) {
        this.contactManager = contactManager;
    }

    public List getContacts() {
        return contacts;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String contactId = getRequest().getParameter("contact.id");
            if (contactId != null && !contactId.equals("")) {
                contact = contactManager.get(new Long(contactId));
            }
        }
    }

    public String list() {
        contacts = contactManager.getAll();
        return SUCCESS;
    }

    public void setId(Long  id) {
        this. id =  id;
    }

    public Contact getContact() {
        return contact;
    }

    public void setContact(Contact contact) {
        this.contact = contact;
    }

    public String delete() {
        contactManager.remove(contact.getId());
        saveMessage(getText("contact.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            contact = contactManager.get(id);
        } else {
            contact = new Contact();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (contact.getId() == null);

        contactManager.save(contact);

        String key = (isNew) ? "contact.added" : "contact.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}